package com.ruoyi.web.controller.order;


import cn.hxzy.common.PaymentStatus;
import cn.hxzy.common.WayBillSignStatus;
import cn.hxzy.common.WaybillStatus;
import cn.hxzy.entity.order.Waybill;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxzy.order.entity.TlLoaderUnloadLog;
import com.hxzy.order.entity.TlWaybillLog;
import com.hxzy.order.entity.TtWaybill;
import com.hxzy.order.entity.vo.WaybillVo;
import com.hxzy.order.service.TlLoaderUnloadLogService;
import com.hxzy.order.service.TlWaybillLogService;
import com.hxzy.order.service.TtAbnormalReportingService;
import com.hxzy.order.service.TtWaybillService;
import com.hxzy.site.entity.TtSite;
import com.hxzy.site.service.TtSiteService;
import com.hxzy.source.entity.TtSourceList;
import com.hxzy.source.service.TtSourceListService;
import com.hxzy.user.entity.TmUser;
import com.hxzy.user.service.TmUserService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.zip.ZipEntry;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mingqian.Wu
 * @since 2023-06-27
 */
@RestController
@RequestMapping("/ttWaybill")
@DataSource(DataSourceType.ORDER)
public class TtWaybillController {

    @Autowired
    private TtWaybillService ttWaybillService;

    @Autowired
    private TtSourceListService ttSourceListService;

    @Autowired
    private TtSiteService ttSiteService;

    @Autowired
    private TlWaybillLogService tlWaybillLogService;

    @Autowired
    private TmUserService tmUserService;

    @Autowired
    private TlLoaderUnloadLogService tlLoaderUnloadLogService;


    @Autowired
    private TtAbnormalReportingService ttAbnormalReportingService;


    @Value("${oss-img-path}")
    private String ossImgPath;


    @GetMapping("/getWaybillList/{pageIndex}/{pageSize}")
    public AjaxResult getWaybillList(@PathVariable Integer pageIndex, @PathVariable Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        List<TtWaybill> list = ttWaybillService.list();
        list.stream().forEach(item -> {
            item.setWaybillStatusName(WaybillStatus.getWaybillStatusValue(item.getWaybillStatus()));
            item.setSigningStatusName(WayBillSignStatus.getSignTypeValue(item.getSigningStatus()));
            item.setPaymentStatusName(PaymentStatus.getPaymentStatusValue(item.getPaymentStatus()));
        });
        PageInfo<TtWaybill> pageInfo = new PageInfo<>(list);
        return AjaxResult.success(pageInfo.getList()).put("total", pageInfo.getTotal());
    }

    @GetMapping("/getWaybillByStatus/{pageIndex}/{pageSize}/{status}")
    public AjaxResult getWaybillByStatus(@PathVariable Integer status, @PathVariable Integer pageIndex, @PathVariable Integer pageSize) {
        QueryWrapper<TtWaybill> queryWrapper = new QueryWrapper<>();
        if (status == 101) {
            queryWrapper.eq("payment_status", 101);
        } else {
            queryWrapper.eq("waybill_status", status);
        }


        PageHelper.startPage(pageIndex, pageSize);
        List<TtWaybill> list = ttWaybillService.list(queryWrapper);
        list.stream().forEach(item -> {
            item.setWaybillStatusName(WaybillStatus.getWaybillStatusValue(item.getWaybillStatus()));
            item.setSigningStatusName(WayBillSignStatus.getSignTypeValue(item.getSigningStatus()));
            item.setPaymentStatusName(PaymentStatus.getPaymentStatusValue(item.getPaymentStatus()));
        });
        PageInfo<TtWaybill> pageInfo = new PageInfo<>(list);
        return AjaxResult.success(pageInfo.getList()).put("total", pageInfo.getTotal());
    }


    @PostMapping("searchWaybill/{pageIndex}/{pageSize}")
    public AjaxResult searchWaybill(@PathVariable Integer pageIndex, @PathVariable Integer pageSize, @RequestBody TtWaybill ttWaybill) {
        PageHelper.startPage(pageIndex, pageSize);
        List<TtWaybill> ttWaybills = ttWaybillService.searchWaybill(ttWaybill);
        ttWaybills.stream().forEach(item -> {
            item.setWaybillStatusName(WaybillStatus.getWaybillStatusValue(item.getWaybillStatus()));
            item.setSigningStatusName(WayBillSignStatus.getSignTypeValue(item.getSigningStatus()));
            item.setPaymentStatusName(PaymentStatus.getPaymentStatusValue(item.getPaymentStatus()));
        });
        PageInfo<TtWaybill> pageInfo = new PageInfo<>(ttWaybills);
        return AjaxResult.success(pageInfo.getList()).put("total", pageInfo.getTotal());
    }


    @GetMapping("/getWaybillInfo/{id}")
    @Anonymous
    public AjaxResult getWaybillInfo(@PathVariable String id) {
        WaybillVo waybillVo = new WaybillVo();
        TtWaybill item = ttWaybillService.getById(id);
        item.setWaybillStatusName(WaybillStatus.getWaybillStatusValue(item.getWaybillStatus()));
        item.setSigningStatusName(WayBillSignStatus.getSignTypeValue(item.getSigningStatus()));
        item.setPaymentStatusName(PaymentStatus.getPaymentStatusValue(item.getPaymentStatus()));
        BeanUtils.copyBeanProp(waybillVo, item);
        TtSourceList sourceById = ttSourceListService.getSourceById(item.getSourceId());
        //装车编号
        String loadingSiteId = sourceById.getLoadingSiteId();
        //卸车编号
        String unloadingSiteId = sourceById.getUnloadingSiteId();

        /*车牌号*/
        waybillVo.setCarId(item.getLicensePlateNumber());

        waybillVo.setSettlerName(sourceById.getSettlerId());
        /*根据装车编号查询站点相关信息*/
        TtSite sourceOne = ttSiteService.getSourceOne(loadingSiteId);
        waybillVo.setVendorName(sourceById.getVendorName());
        waybillVo.setLoadingSiteName(sourceOne.getName());
        waybillVo.setLoadingAddress(sourceOne.getLocation());

        /*根据卸车编号查询站点相关信息*/
        TtSite sourceOne1 = ttSiteService.getSourceOne(unloadingSiteId);
        waybillVo.setUnloadingSiteName(sourceOne1.getName());
        waybillVo.setUnloadingAddress(sourceOne1.getLocation());

        /*查询运单时间信息*/
        TlWaybillLog waybillLogById = tlWaybillLogService.getWabillLogById(id);
        waybillVo.setLogList(waybillLogById);
        /*货物名称*/
        waybillVo.setNameOfGood(sourceById.getGoodsName());

        /*查询司机相关信息*/
        TmUser userById = tmUserService.getUserById(item.getDriverId());
        waybillVo.setDriverName(userById.getUserName());
        waybillVo.setDriverPhone(userById.getUserPhone());



        /*查询装卸车磅单信息*/
        List<TlLoaderUnloadLog> loaderUnloagList = tlLoaderUnloadLogService.getLoaderUnloagList(id);


        waybillVo.setLossCost(sourceById.getLossCost());

        if (loaderUnloagList.size() > 0) {
            loaderUnloagList.stream().forEach(item1 -> {
                if ("UN".equals(item1.getId().split("-")[0])) {
                    BigDecimal suttle = item1.getSuttle();
                    BigDecimal multiply = suttle.multiply(sourceById.getSourceFreight());
                    waybillVo.setTransportationAmount(multiply);
                    item1.setGoodsImgUrl(ossImgPath + item1.getGoodsImgUrl());
                    item1.setPoundImgUrl(ossImgPath + item1.getPoundImgUrl());
                    System.out.println("---" + waybillVo.getTransportationAmount());
                    /*含税运价的运输金额*/
                    BigDecimal sourceFreightTax = sourceById.getSourceFreightTax();
                    BigDecimal multiply1 = sourceFreightTax.multiply(suttle);
                    waybillVo.setSourceFreight(sourceById.getSourceFreight());
                    waybillVo.setSourceFreightTax(sourceById.getSourceFreightTax());
                    waybillVo.setTransportationAmountShui(multiply1);
                    waybillVo.setUnloadInfo(item1);
                } else {
                    TlLoaderUnloadLog tlWaybillLog = new TlLoaderUnloadLog();
                    waybillVo.setUnloadInfo(tlWaybillLog);
                }

                if ("LD".equals(item1.getId().split("-")[0])) {
                    item1.setGoodsImgUrl(ossImgPath + item1.getGoodsImgUrl());
                    item1.setPoundImgUrl(ossImgPath + item1.getPoundImgUrl());
                    waybillVo.setLoaderInfo(item1);
                } else {
                    TlLoaderUnloadLog tlWaybillLog = new TlLoaderUnloadLog();
                    waybillVo.setLoaderInfo(tlWaybillLog);
                }
            });
        } else {
            TlLoaderUnloadLog tlWaybillLog = new TlLoaderUnloadLog();
            waybillVo.setLoaderInfo(tlWaybillLog);
            waybillVo.setUnloadInfo(tlWaybillLog);
        }

        return AjaxResult.success(waybillVo);
    }


    @GetMapping("cancelWaybill/{id}")
    public AjaxResult cancelWaybill(@PathVariable String id) {
        UpdateWrapper<TtWaybill> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("waybill_id", id);
        updateWrapper.set("waybill_status", 105);
        boolean update = ttWaybillService.update(updateWrapper);
        if (update) {
            return AjaxResult.success("已取消运单");
        }
        return AjaxResult.error("取消失败");
    }


}

